#include "common.h"
#include <stdio.h>
#include <stdlib.h>

#define MSF2SECT(m,s,f)	(((m)*60+(s)-2)*75+(f))
#define btoi(b)		((b)/16*10 + (b)%16)		// BCD to u_char   29 
#define CD_FRAMESIZE_RAW	2352
#define DATA_SIZE	(CD_FRAMESIZE_RAW-12)

FILE* cdHandle;
unsigned char cdBuffer[CD_FRAMESIZE_RAW * 10];

char * CALLBACK PSEgetLibName(void)
{
	return LIBRARY_NAME;
}

unsigned long CALLBACK PSEgetLibType(void)
{
	return 1;
}

unsigned long CALLBACK PSEgetLibVersion(void)
{
	return VERSION_MAJOR<<16|VERSION_MINOR<<8|VERSION_REV;
}

long CALLBACK CDRinit(void)
{
	cdHandle = NULL;
	return 0;
}

long CALLBACK CDRshutdown(void)
{
	return 0;
}

long CALLBACK CDRopen(void)
{
	// run gui to get the file path.
	char fileName[256];

	if (cdHandle != NULL)
		return 0;

	if (SysOpenFile(fileName) != 0)
		return -1;

	// got the file path..
	cdHandle = fopen(fileName, "rb");
	if (cdHandle == NULL) return -1;

	// TODO: parse toc.

	return 0;
}

long CALLBACK CDRclose(void)
{
	if (cdHandle == NULL)
		return 0;
	fclose(cdHandle);
	cdHandle = NULL;
	return 0;
}

long CALLBACK CDRgetTN(unsigned char *buffer)
{
	buffer[0] = 1;
	// TODO: CDDA support!
	buffer[1] = 1;
	return 0;
}

long CALLBACK CDRgetTD(unsigned char track, unsigned char *buffer)
{
	buffer[0] = buffer[2] = 0;
	buffer[1] = 2;

	return 0;
}

long CALLBACK CDRreadTrack(unsigned char *time)
{
	if (cdHandle == NULL)
		return -1;

	fseek(cdHandle, MSF2SECT(btoi(time[0]), btoi(time[1]), btoi(time[2])) * CD_FRAMESIZE_RAW + 12, SEEK_SET);
	fread(cdBuffer, 1, DATA_SIZE, cdHandle);

	return 0;
}

unsigned char * CALLBACK CDRgetBuffer(void)
{
	return cdBuffer;
	return 0;
}

long CALLBACK CDRconfigure(void)
{
	return 0;
}

long CALLBACK CDRtest(void)
{
	return 0;
}

void CALLBACK CDRabout(void)
{
}

long CALLBACK CDRplay(unsigned char *sector)
{
	return 0;
}

long CALLBACK CDRstop(void)
{
	return 0;
}

long CALLBACK CDRgetStatus(struct CdrStat *stat)
{
	return 0;
}

char* CALLBACK CDRgetDriveLetter(void)
{
	return 0;
}

unsigned char* CALLBACK CDRgetBufferSub(void)
{
	return 0;
}